package com.hzcc.hzccblog.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author 早睡蛋
 * @Date 2022/6/12 14:39:16
 * @Desc:图片上传工具类
 */
@Component
@Service
public class FileUpdateUtil {

    /**
     * 文章图片添加
     * @param file
     * @param articleImages
     * @return
     */
    public Map updateArticlePic(MultipartFile file,String articleImages) {
        Map<String,String> map = new HashMap<>();
        try {
            String fileName = IDUtil.createByTimeMillis()+file.getOriginalFilename();
            //实际地址
            String filePath = articleImages;
            file.transferTo(new File(filePath,fileName));
            //储存在数据库中的地址
            String dataPath = "/article/images/"+fileName;
            //前端映射地址
            String fileUrl = "http://localhost:8785/article/images/"+fileName;
            map.put("dataPath",dataPath);
            map.put("fileUrl",fileUrl);
            map.put("desc",fileName);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return map;
    }

    /**
     * 更新头像
     * @param file
     * @param myAvator
     * @return
     */
    public Map updateAvator(MultipartFile file, String myAvator,String oldAvator){
        Map<String,String> map = new HashMap<>();
        try {
            String filePath = myAvator;
            File file2 = new File(filePath, oldAvator);
            if (file2.exists()) file2.delete();//删除原有地址
            String fileName = IDUtil.createByTimeMillis()+file.getOriginalFilename();
            //实际地址
            file.transferTo(new File(filePath,fileName));
            //储存在数据库中的地址
            String dataPath = "/myAvator/"+fileName;
            //前端映射地址
            String fileUrl = "http://localhost:8785/myAvator/"+fileName;
            map.put("dataPath",dataPath);
            map.put("fileUrl",fileUrl);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return map;
    }

}
